package com.roadmap.client.common;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import com.roadmap.common.BaseEntity;

public class ResultSet implements IResultSet {
	/** entity owns the result set */
	private BaseEntity ownerEntity;
	/**
	 * the param String is the id of owner entity who owns the result set
	 * defined in hash table.
	 */
	private Hashtable<String, IResultSet> childEntities;

	public ResultSet() {
		this.childEntities = new Hashtable<String, IResultSet>();
	}

	/** maybe the result set has no owner, and also may have no kids */
	public ResultSet(BaseEntity ownerEntity, boolean hasChild) {
		this.ownerEntity = ownerEntity;
		if (hasChild)
			this.childEntities = new Hashtable<String, IResultSet>();
		else
			this.childEntities = null;
	}

	public BaseEntity getOwner() {
		return ownerEntity;
	}

	public void setOwner(BaseEntity owner) {
		this.ownerEntity = owner;
	}

	public void addChild(IResultSet rs) {
		if (rs == null || rs.getOwner() == null || childEntities == null) {
			return;
		}
		String id = rs.getOwner().getId();
		if (id == null)
			return;
		childEntities.put(id, rs);
	}

	public BaseEntity getChild(String id) {
		if (childEntities == null || id == null)
			return null;
		IResultSet rs = childEntities.get(id);
		BaseEntity ent = null;
		if (rs != null)
			ent = rs.getOwner();
		return ent;

	}

	public IResultSet getChildSet(String id) {
		if (childEntities == null || id == null)
			return null;
		IResultSet rs = childEntities.get(id);
		return rs;
	}

	public List<BaseEntity> getAllChilren() {
		if (childEntities == null)
			return null;
		List<BaseEntity> entities = new ArrayList<BaseEntity>();
		Iterator<IResultSet> iter = childEntities.values().iterator();
		while (iter.hasNext()) {
			IResultSet rs = iter.next();
			BaseEntity ent = rs.getOwner();
			if (ent != null)
				entities.add(ent);
		}

		return entities;
	}

	public void cleanup() {
		remove(this);
	}

	private void remove(IResultSet rs) {
		if (rs != null) {
			Iterator<IResultSet> iter = childEntities.values().iterator();
			while (iter.hasNext()) {
				remove(iter.next());
			}
			ownerEntity = null;
			childEntities.clear();
			childEntities = null;
		}

	}
}
